api = window.TS.api
appPath = window.TS.appPath
app = window.TS.app
routers = {}
window.TS.Routers = routers

#test data
data1 =
{
    id: 111,
    name: "问题1",
    type: "BUG",
    level: "正常",
    status: "新建",
    desc: "问题描述问题描述",
    details: "- - -",
    comment: "- - -",
    createTime: api.formatDate(),
    modifyTime: api.formatDate(),
    version: "1.0",
    publishTime: api.formatDate()
}

data2 =
{
    id: 222,
    name: "问题2",
    type: "BUG",
    level: "正常",
    status: "开发中",
    desc: "问题描述问题描述问题描题描述",
    details: "- - -",
    comment: "- - -",
    createTime: api.formatDate(),
    modifyTime: api.formatDate(),
    version: "1.0",
    publishTime: api.formatDate()
}

data3 =
{
    id: 333,
    name: "问题3",
    type: "BUG",
    level: "正常",
    status: "开发完成",
    desc: "问题描述",
    details: "- - -",
    comment: "- - -",
    createTime: api.formatDate(),
    modifyTime: api.formatDate(),
    version: "1.0",
    publishTime: api.formatDate()
}

data4 =
{
    id: 444,
    name: "问题4",
    type: "BUG",
    level: "正常",
    status: "解决",
    desc: "- - -",
    details: "- - -",
    comment: "- - -",
    createTime: api.formatDate(),
    modifyTime: api.formatDate(),
    version: "1.0",
    publishTime: api.formatDate()
}

json = [data1, data2, data3, data4, data4]

routers = Backbone.Router.extend
    routes:
        "": "index"
        "index": "index"

    index: ->
        alert 1

router = new routers();
Backbone.history.start({pushState: true});


statusTranslate = (status)->
    switch status
        when "新建" then "todo"
        when "开发中" then "in-progress"
        when "开发完成" then "ready-for-test"
        when "解决" then "done"
        when "拒绝" then "refuse"
        when "反馈" then "feedback"

app.showTasks = ->
    if json
        $('.control .show-item').hide();
        $('.content.table').hide()
        $('.control .show').attr "class", "show show-block"
        $('.content.tasks').show()
        $(".tasks .task").remove()
        for data in json
            for key,val of data
                status = val if key is "status"
                id = val if key is "id"
                name = val if key is "name"
                desc = val if key is "desc"
            status = statusTranslate status
            $("<div>",
                class: "task"
                taskId: id
                html: "<div>#{name}</div><div>#{desc}</div>")
            .appendTo ".#{status} .task-content";

app.showTask = (relativeUrl, data)->
    $('#bcMark').show()
    api.get(relativeUrl, data)
    .done((responseHTML, status)->
        $dialog = $(responseHTML)
        if data
            for key,val of data
                do (key) ->
                    nodeName = if $dialog.find("[name=#{key}]")[0] then $dialog.find("[name=#{key}]")[0].nodeName else ""
                    $dialog.find("[name=#{key}]").val(val)
                    $dialog.find("[name=#{key}]").html(val) if nodeName.toLocaleLowerCase() isnt "select"
        else
            $dialog.find('[name=createTime]').val(api.formatDate())
            $dialog.find('[name=createTime]').html(api.formatDate())
            $dialog.find('[name=modifyTime]').val(api.formatDate())
            $dialog.find('[name=modifyTime]').html(api.formatDate())
        $dialog.appendTo("#taskDialog"))

app.showTable = ->
    listKey = [];
    $('.show-item .selected').each (i, e)->
        listKey.push $(this).attr "key"
    tBody = ""
    for data in json
        td = ""
        for key,val of data
            if key in listKey
                td += "<td key=#{key}>#{val}</td>"
            else
                td += "<td key=#{key} style='display: none'>#{val}</td>"
        tBody += "<tr>#{td}</tr>"

    $('.content.table table').find('tbody').html(tBody)

    $('.content.tasks').hide()
    $('.control .show').attr "class", "show show-table"
    $('.control .show-item').show();
    $('.content.table').show()
    $('.content.table tbody tr:first-child').click()

app.hideGitStats = ->
    $(".git-stats").hide()

app.showGitStats = ->
    gitStatsData = TS.gitStatsData
    return if !gitStatsData
    len = gitStatsData.length
    $gitList = $(".git-stats .git-list")
    $gitList.empty()
    $ul = $('<ul>').appendTo $gitList
    for i in [0...len]
        name = gitStatsData[i].name
        statsDir = gitStatsData[i].statsDir
        $li = $('<li>').appendTo $ul
        $a = $('<a>',
            "class": "git-name"
            "text": name
            "html": name
        ).data("statsDir", statsDir).appendTo $li
    $('.content').hide()
    $('.control').hide()
    $(".git-stats").show()

$('.git-list')
.on "click", ".git-name", ->
    statsDir = $(this).data("statsDir")
    return if !statsDir
    api.get(statsDir, "")
    .done((responseHTML, status)->
        $('.git-avcivity').html($('body', responseHTML))
    )

$('body')
.on "click", "*.main-nav li", ->
    $tab = $(this)
    $tab.addClass("active").siblings().removeClass("active")
    switch $tab.attr "name"
        when "show-tasks"
            app.hideGitStats()
            app.showTasks()
        when "load-table"
            app.hideGitStats()
            app.showTable()
        when "show-gitStats"
            app.showGitStats()

# show a task
$('body')
.on "click", ".main-content .task", ->
    if $(this).hasClass 'selected'
        app.showTask "/page/taskDetails.html", data1
    else
        $('.main-content .task').removeClass 'selected'
        $(this).addClass 'selected'

# add a new task
$('body')
.on "click", ".add-task", ->
    app.showTask("/page/taskDetails.html")

# delete a new task
$('body')
.on "click", ".del-task", ->
    app.deleteTask()
    $(this).blur()

# close task
$('body')
.on "click", ".task-details .close", ->
    $('#bcMark').hide()
    $('#taskDialog').empty()

# save task
$('body')
.on "click", ".task-details .save", ->
    id = $('.task-details [name="id"]').val() || 0;
    if id <= 0
        app.addNewTask()
    else
        app.editTask id
    $('#bcMark').hide()
    $('#taskDialog').empty()

app.addNewTask = ->
    modifyTaskHTML(0)

app.editTask = (id)->
    modifyTaskHTML(id)

#TODO:delete from the backend
app.deleteTask = ()->
    if $('.main-nav li[name="show-tasks"]').hasClass "active"
        if $('.tasks .selected').length > 0
            $('.tasks .selected').remove()
        else
            alert "请选择要删除的问题"
    else
        if $('.table .selected').length > 0
            $('.table .selected').remove()
            $('.content.table tbody tr:first-child').click();
        else
            alert "请选择要删除的问题"

modifyTaskHTML = (id)->
    data = $('.task-details form').serializeObject()
    if $('.content.table').is(":hidden")
        for key,val of data
            status = val if key is "status"
            name = val if key is "name"
            desc = val if key is "desc"
        status = statusTranslate status
        html = "<div>#{name}</div><div>#{desc}</div>"
        if id > 0 #edit
            $("[taskId=#{id}]").html(html);
        else #add
            $('.tasks .selected').removeClass "selected"
            $("<div>", {
                class: "task selected"
                html: html
            }).appendTo($(".#{status} .task-content"));
    else
        td = ""
        listKey = [];
        $('.show-item .selected').each (i, e)->
            listKey.push $(this).attr "key"
        for key,val of data
            if key in listKey
                td += "<td key=#{key}>#{val}</td>"
            else
                td += "<td key=#{key} style='display: none;'>#{val}</td>"
        if id > 0 #edit
            $(".content.table tbody td:contains(#{id})").parent().html(td);
        else  #add
            $("<tr>#{td}</tr>").insertBefore($('.content.table tbody tr:first-child'))
            $('.content.table tbody tr:first-child').click();


$('body')
.on "click", ".main-content .control .show", ->
    if $(this).hasClass "show-block"
        $('.main-nav li[name="load-table"]').click()
    else
        $('.main-nav li[name="show-tasks"]').click()

$(".task").draggable(
    containment: ".tasks"
    deactivate: (event, ui)->
        $(this).appendTo
        $(ui)
)
$(".tasks > div").droppable()

$('.main-nav [name="show-tasks"]').click()